package com.rerun.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rerun.common.bean.Rest;
import com.rerun.entity.JobFeedback;
import com.rerun.entity.MemberPost;
import com.rerun.enums.ResumeStateEnum;
import com.rerun.mapper.JobFeedbackMapper;
import com.rerun.mapper.MemberPostMapper;
import com.rerun.service.IJobService;
import com.rerun.service.IMailService;
import com.rerun.service.IMemberPostService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * 简历投递
 *
 * @author dax.
 * @version v1.0
 * @see ResumeStateEnum 简历状态详情定时任务
 * @see com.rerun.task.FeedbackDetailTask
 * @since 2017 /10/12 9:48
 */
@Service
public class MemberPostServiceImpl extends ServiceImpl<MemberPostMapper, MemberPost> implements IMemberPostService {

    @Resource
    private JobFeedbackMapper jobFeedbackMapper;
    @Resource
    private MemberPostMapper memberPostMapper;
    @Resource
    private IMailService iMailService;



    @Override
    public Rest postResume(HttpServletRequest request, String memberId, String jobId) throws IOException, MessagingException {
        if (selectForVerify(memberId, jobId)) {
            MemberPost post = new MemberPost();
            post.setMemberId(memberId);
            post.setJobId(jobId);
            long status = Long.valueOf(ResumeStateEnum.post.getKey());
            post.setStatus(status);
            Date currentDate = new Date();
            post.setCreateTime(currentDate);
            memberPostMapper.insert(post);

            JobFeedback jobFeedback = new JobFeedback();
            jobFeedback.setMemberId(memberId);
            jobFeedback.setJobId(jobId);
            jobFeedback.setStatus(status);
            jobFeedback.setCreateTime(currentDate);
            jobFeedbackMapper.insert(jobFeedback);
            //           detail 通过定时任务生成
             iMailService.sendResumeEmail(request, memberId, jobId);
             return Rest.ok();
        }
        return Rest.forbidden("对同一职位每30天只能投递1次");
    }



    @Override
    public boolean selectForVerify(String memberId, String jobId) {

        MemberPost post = memberPostMapper.selectForVerify(memberId, jobId);
        if (Objects.nonNull(post)) {
            Date date = post.getCreateTime();
            Date now = new Date();
            long time = date.getTime() - now.getTime();
            return time / (24 * 60 * 60 * 1000) > 30;
        }
        return true;
    }
}
